package com.easy.leetcode.array;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName CombinationSum40
 * @Description 40. 组合总和 II
 * @Author zheng
 * @Date 2021/11/24 19:02
 * @Version 1.0
 **/
public class CombinationSum40 {
    List<List<Integer>> result = new ArrayList<>();
    List<Integer> path = new ArrayList<Integer>();

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        backTracking(candidates, target, 0, 0);
        return result;
    }

    /**
     * @return void
     * @Description 回溯
     * @Date 2021/11/24 19:56
     * @Param [candidates 数组, target 目标值, sum 当前值, index 开始索引]
     **/
    public void backTracking(int[] candidates, int target, int sum, int index) {
        //当前值与目标值相等，记录当前数组，需要new 一个
        if (sum == target) {
            result.add(new ArrayList<>(path));
            return;
        }
        //从开始索引开始循环，
        for (int i = index; i < candidates.length && sum + candidates[index] <= target; i++) {
            if (i > index && candidates[i] == candidates[i - 1]) {
                continue;
            }
            sum += candidates[i];
            path.add(candidates[i]);
            backTracking(candidates, target, sum, i + 1);
            sum -= candidates[i];
            path.remove(path.size() - 1);
        }
    }

    public static void main(String[] args) {
        CombinationSum40 combinationSum40 = new CombinationSum40();
        int[] arr = new int[]{10, 1, 2, 7, 6, 1, 5};
        System.out.println(Arrays.toString(arr));
        System.out.println(combinationSum40.combinationSum2(arr, 8).toString());
    }


}
